const {FlySQL} = require('flysql')
const {shopClass} = require('../tool')
const {
  db: {password, port, host, user},
} = require('../config')

const db = new FlySQL({
  port,
  host,
  user,
  password,
  pool: true,
  database: 'jd',
})

console.log({
  port,
  host,
  user,
  password,
  pool: true,
  database: 'jd',
})

/**按创建时间排序 */
const order = {
  createdAt: 'DESC',
}

/**获取用户 */
const getUser = async (id) => {
  return await db.first({
    form: 'user',
    field: ['username', 'power', 'mail', 'portrait'],
    where: {
      id,
    },
  })
}

db.model({
  user: {
    preprocess: {
      power(value) {
        if (!value) return []
        return value.split(',')
      },
    },
  },
  commodity: {
    createdAt: true,
    updateAt: true,
    deleteAt: true,
    preprocess: {
      tags(value) {
        if (!value) return []
        return value.split(',')
      },
      image(value) {
        if (!value) return []
        return value.split(',')
      },
      specification(value) {
        if (!value) return []
        return value.split(',')
      },
    },
    virtual: {
      async cover(row) {
        if (!row.image) return
        const data = row.image[0]
        delete row.image
        return data
      },
      async shop({shopid: id}) {
        return db.first({
          form: 'shop',
          where: {
            id,
          },
        })
      },
      async brand({brandid: id}) {
        return db.first({
          form: 'brand',
          where: {
            id,
          },
        })
      },
      async classify({classifyid: id}) {
        return db.first({
          form: 'classify',
          where: {
            id,
          },
        })
      },
      async commentCount({id}) {
        return await db.count({
          form: 'comment',
          where: {
            commodityid: id,
          },
        })
      },
    },
  },
  'shopping-cart': {
    createdAt: true,
    virtual: {
      async commodity(data) {
        const id = data['commodityid']
        return await db.first({
          form: 'commodity',
          field: ['id', 'name', 'price', 'stock', 'specification', 'createdAt', 'discount', 'image'],
          virtual: ['cover'],
          where: {
            id,
          },
        })
      },
      async price(data) {
        const id = data['commodityid']
        const dd = await db.first({
          form: 'commodity',
          field: ['price', 'discount'],
          virtual: ['cover'],
          where: {
            id,
          },
        })
        return dd.price * dd.discount / 100
      },
      async shop({shopid: id}) {
        return db.first({
          form: 'shop',
          field: ['id', 'name'],
          where: {
            id,
          },
        })
      },
    },
  },
  classify: {
    deleteAt: true,
    virtual: {
      async child({id}) {
        return db.find({
          form: 'classify',
          where: {
            grade: 2,
            parent: id,
          },
        })
      },
    },
  },
  comment: {
    createdAt: true,
    preprocess: {
      image(value) {
        if (!value) return []
        return value.split(',')
      },
    },
    virtual: {
      async user({userid}) {
        return await getUser(userid)
      },
      async firstReply({id}) {
        return await db.first({
          form: 'comment',
          virtual: ['agree', 'user'],
          where: {
            host: id,
          },
          order,
        })
      },
      async replyUser({reply}) {
        const {userid} = await db.first({
          form: 'comment',
          where: {
            id: reply,
          },
        })
        return await getUser(userid)
      },
      async reply({id}, param) {
        return await db.find({
          form: 'comment',
          field: ['id', 'parent', 'main', 'reply', 'createdAt'],
          virtual: ['agree', 'user', 'replyUser', 'isAgree'],
          where: {
            host: id,
          },
          order: {
            createdAt: true,
          },
          param,
        })
      },
      async replyCount({id}) {
        return await db.count({
          form: 'comment',
          field: ['id', 'parent', 'main'],
          virtual: ['agree', 'user'],
          where: {
            host: id,
          },
        })
      },
      async agree({id}) {
        return await db.count({
          form: 'comment-agree',
          where: {
            commentid: id,
          },
        })
      },
      async isAgree({id}, user) {
        if (!user) return null
        return await db.count({
          form: 'comment-agree',
          where: {
            userid: user.id,
            commentid: id,
          },
        })
      },
    },
  },
  brand: {
    virtual: {
      async classifyList({classifys}) {
        if (!classifys.length) return []
        return await db.find({
          form: 'classify',
          where: {
            id: classifys,
          },
        })
      },
    },
    preprocess: {
      classifys(value) {
        if (!value) return []
        return value.split(',')
      },
    },
  },
  order: {
    createdAt: true,
    preprocess: {
      scid(value) {
        if (!value) return []
        return value.split(',')
      },
    },
    virtual: {
      async shoppingCarts(row) {
        const data = await db.find({
          form: 'shopping-cart',
          where: {
            id: row.scid,
          },
          virtual: ['commodity', 'shop'],
          order: {
            createdAt: 'DESC',
          },
        })
        delete row.scid
        return shopClass(data)
      },
      async shoppingCartCount({scid}) {
        return scid.length
      },
      async cover(row) {
        const data = await db.first({
          form: 'shopping-cart',
          virtual: ['commodity'],
          where: {
            id: row.scid[0],
          },
        })
        delete row.scid
        return data.commodity.cover
      },
    },
  },
})

db.on('format', ({sql}) => {
  console.log(sql)
})

module.exports = db
